package com.freestyle.common.support;

import com.freestyle.common.ResponseEntity;
import com.freestyle.common.models.JSONData;
import com.freestyle.common.models.ModifyDataException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.annotation.PostConstruct;
import javax.servlet.Servlet;

/**
 * Created by rocklee on 2021/12/16 16:24
 */
@Slf4j
@ControllerAdvice
//@ConditionalOnProperty(name="spring.main.web-application-type", havingValue = "SERVLET", matchIfMissing = true)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
public class GlobalExceptionHandler extends  ResponseEntityExceptionHandler {
  @ExceptionHandler(ModifyDataException.class)
  @ResponseBody
  public ResponseEntity<ModifyDataException> handleModifyDataException(ModifyDataException e) {
    String eName = e.getClass().getSimpleName();
    log.error("执行出错：{}",eName);
    ResponseEntity<ModifyDataException> exceptionResponseEntity=ResponseEntity.fromErr(0,e);
    exceptionResponseEntity.put("exception",e);
    return exceptionResponseEntity;
  }
  @ExceptionHandler(Exception.class)
  @ResponseBody
  public ResponseEntity<Exception> handleException(Exception e) {
    String eName = e.getClass().getSimpleName();
    log.error("执行出错：{}",e);
    return JSONData.fromErr(0,e);
  }
  @PostConstruct
  public void init(){
    log.info("GlobalException handler inited.");
  }
}
